<template>
  <div class="standardAddcon">
    <div class="twoStageWindow">
      <div class="twoStageWindowTitle">
        {{newOrEdit=='new'?'新增':(newOrEdit=='edit'?'编辑':'查看')}}评价标准
        <div class="twoStageWindowClose" v-if="newOrEdit != 'review'">

          <!--{{canEdit}}-->
          <!--{{isStatus}}-->
          <!--草稿和新增状态有提交和保存-->
          <!--启用状态有生成新版本，没有保存-->
          <!--{{canEdit}} -->
          <el-button size="mini" type="primary" v-on:click="submitStandard('commit')" v-if="newOrEdit != 'look' && standardForm.hasCommit" :disabled="!isRepeat">提交</el-button>
          <el-button size="mini" type="primary" @click="submitStandard('save')" v-if="newOrEdit == 'new' || (isStatus == 2 && newOrEdit != 'look')"
            :disabled="!isRepeat">保存</el-button>
          <el-button size="mini" v-on:click="close('standardForm')">取消</el-button>
        </div>
        <div class="twoStageWindowClose" v-if="newOrEdit == 'review'">
          <el-button type="primary" @click="reviewFlowPop" size="mini">审核</el-button>
          <el-button size="mini" v-on:click="close('standardForm')">取消</el-button>
        </div>
      </div>
      <div class="containercontent" style="margin-top:40px;height:calc(100% - 40px);padding-top: 0;">
        <div class="form">
          <el-form style="height:100%;" label-width="110px" :inline="false" class="demo-form-inline standardForm" :model="standardForm"
            :rules="standardRules" ref="standardForm">
            <el-form-item label="标准名称" prop='name'>
              <el-col :span="22">
                <el-input size="mini" v-model="standardForm.name" placeholder="请输入内容" :disabled="!canEdit"></el-input>

              </el-col>
            </el-form-item>
            <!--<el-form-item label="编号" prop="code">
              <el-col :span="22">
                <el-input size="mini" placeholder="标准编号" disabled v-model="standardForm.code"></el-input>
              </el-col>
            </el-form-item>-->
            <el-form-item label="标准号" prop='version'>
              <el-col :span="22">
                <el-input size="mini" v-model="standardForm.version" placeholder="请输入内容" :disabled="!canEdit"></el-input>

              </el-col>
            </el-form-item>
            <el-form-item label="分类" prop='type'>
              <el-col :span="22">
                <el-select size="mini" v-model="standardForm.type" :disabled="!canEdit">
                  <el-option v-for="item in sampleSelect.itemList" :key="item.code" :label="item.name" :value="item.code">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="实施日期" prop="publishedDate">
              <el-col :span="22">
                <el-date-picker v-model="standardForm.publishedDate" type="date" size="mini" placeholder="选择日期" format='yyyy-MM-dd' value-format='yyyy-MM-dd'
                  :disabled="!canEdit">
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="描述" prop='description'>
              <el-col :span="22">
                <el-input size="mini" v-model="standardForm.description" placeholder="请输入内容" :disabled="!canEdit"></el-input>
              </el-col>
            </el-form-item>


          </el-form>
        </div>
        <div class="elTab">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="评价指标" name="first">
              <div style="height: 38px;float:right">
                <el-button type="primary" size="mini" @click="addAnalysis" icon="el-icon-plus" v-if="newOrEdit != 'look' && newOrEdit != 'review'"
                  :disabled="isStatus == '1' || !isRepeat">添加指标</el-button>
              </div>
              <el-table :data="standardForm.itemBeanList" style="width: 100%;height:calc(100% - 38px)" class="tableCon" size="mini">
                <el-table-column label="序号" min-width="50px">
                  <template slot-scope="scope">
                    {{scope.$index+1}}
                  </template>
                </el-table-column>
               <el-table-column property="itemName" label="项目名称" min-width="100px">
                </el-table-column>
                <el-table-column property="indexName" label="指标名称" min-width="100px">
                    <template slot-scope="scope">
                    <el-input v-model="scope.row.indexName" size="mini" placeholder="请输入内容" :disabled="!canEdit"></el-input>
                  </template>
                </el-table-column>
                <el-table-column property="unit" label="单位" min-width="100px">
                  <template slot-scope="scope">
                    <!--<el-input v-model="scope.row.unit" size="mini" placeholder="请输入内容" :disabled="!canEdit"></el-input>-->

                    <el-select v-model="scope.row.unit" size="mini" filterable :disabled="!canEdit || isStatus == '1'">
                      <el-option v-for="item in allUnit" :key="item.code" :label="item.ename" :value="item.code">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                
                <el-table-column label="操作" min-width="100px" v-if="newOrEdit != 'look' && newOrEdit != 'review' ">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="deleteItem(scope.$index)" :disabled="isStatus == '1'">删除</el-button>
                    <el-button type="text" size="mini" @click="ascQcStandar(scope.row,scope.$index)"  v-if = "newOrEdit == 'edit' || newOrEdit == 'new'">上移</el-button>
                    <el-button type="text" size="mini" @click="descQcStandar(scope.row,scope.$index)"  v-if = "newOrEdit == 'edit' || newOrEdit == 'new'">下移</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="审核信息" name="second" v-if="(newOrEdit == 'look') && standardForm.status != 2 && (standardForm.source == '' || standardForm.source == null || standardForm.source == undefined )">
              <div id="myIframe" v-loading="loading1" style = "text-align:center">
                <span style = "color:#909399;line-height:100px;" v-if = "WorkFlowMsg != '' && WorkFlowMsg != undefined" >{{WorkFlowMsg}}</span>
                <iframe :src="url" id="workFlowIframe" ref="workFlowIframe" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>
              </div>
            </el-tab-pane>

          </el-tabs>
        </div>
      </div>
      <div class="user-footer" v-if="newOrEdit == 'look'">
        <span>
                创建人:{{standardForm.createBy}}
              </span>
        <span>
                创建时间:{{standardForm.createTime}}
              </span>
        <span v-if="standardForm.updateBy != undefined">
                修改人：{{standardForm.updateBy}}
              </span>
        <span v-if="standardForm.updateTime != undefined">
                修改时间：{{standardForm.updateTime}}
              </span>
      </div>

    </div>
    <el-dialog :visible.sync="analysisAddShow" width="55%" :show-close='false' :closeOnClickModal='false' class="analysisForm"
      ref="analysisForm">
      <span slot="title" class="dialog-title">
          选择指标
          <el-button @click="closeAnalysis('analysisForm')" size="mini" class="popupClose">关闭</el-button>
        </span>
      <div class="penalrow selectw100 form" style = "padding-top:0">
        <div class=" width100 ">
          <div class="inlineblock verticalmiddle">
            标准名称
          </div>
          <div class="inlineblock verticalmiddle informationItem">
            <el-input size="mini" placeholder="标准名称" v-model="standardForm.name" disabled></el-input>
          </div>
        </div>
      </div>
      <div style="width:100%;float:right;" class="analysisitem">
        <analysisitem :isZuJian="true" :index="true" :noadd="false" ref="analysisitem" v-on:selectedItem="selectedItem" :userOpernation="$parent.userOpernation"></analysisitem>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addItem" size="mini">确定</el-button>
          <el-button  size="mini" @click="closeAnalysis('analysisForm')">取 消</el-button>
        </span>
    </el-dialog>
    <!---->
    <review-flow :addVisible.sync="reviewFlowShow" :reviewData="reviewData" :procInstType="procInstType" :reviewTitle="reviewTitle"
      @reloadMain="closeRefresh"></review-flow>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  const analysisitem = () => import('../../analysisitem/analysisitem.vue');
  const reviewFlow = () =>
		import('../../../../common/reviewFlow.vue');

  export default {
    data() {
      var that = this;
      return {
        standardForm: {
          name: '',
          status: 2,
          code: "",
          type: "",
          publishedDate: "",
          description: "",
          parentVersion: "",
          version: "",
          sort: "1",
          itemBeanList: []
        },
        standardRules: {
          name: [
            { required: true, type: 'string', message: '请填写名称', trigger: 'blur' },
          ],
          version: [{ required: true, type: 'string', message: '请填写标准号', trigger: 'blur' }],
          type: [{ required: true, type: 'string', message: '请选择类型', trigger: 'change' }],
          publishedDate: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        analysisForm: {},
        analysisRules: {},
        analysisItemTableDate: [],
        selectedItemval: [], //选中的指标
        // 截至日期不能选择发布日期之前的日期
        // pickerOptions: {
        //   disabledDate(time) {
        //     if (that.standardForm.publishedDate != '') {
        //       let publishedDate = new Date(that.standardForm.publishedDate);
        //       return time.getTime() < publishedDate.getTime() - 8.64e7;
        //     }

        //   }
        // },
        loading: false,
        isStatus: '',
        isRepeat: true,
        reviewFlowShow: false, //审核流显示
        reviewData: null, //点击行需要审核的信息
        procInstType: 't_standard', //审核流要查的表
        reviewTitle: '评价标准',
        activeTab: "first",
        url: "",
        loading1: true,
        WorkFlowMsg:"",

        yesornoValue: '1',
        enableStatusValue: '1',
        analysisAddShow: false,
        itemStatus: '',
        itype: true
      }
    },
    components: {
      analysisitem, reviewFlow
    },
    computed: {
      ...mapState(['enableStatus', 'sampleSelect', 'yesorno', 'objectSelect', 'submitType']),
    },
    props: ['newOrEdit', 'canEdit', 'status', 'standardDetail',"allUnit"],
    created() {
      this.$store.dispatch('dogetDictionary');
      for (var i in this.standardDetail) { //赋值
        this.standardForm[i] = this.standardDetail[i];
      }
      for(var i in this.standardForm.itemBeanList){
        if(this.standardForm.itemBeanList[i].indexName == undefined || this.standardForm.itemBeanList[i].indexName == "" || this.standardForm.itemBeanList[i].indexName == null  ){
          this.$set(this.standardForm.itemBeanList[i],"indexName",this.standardForm.itemBeanList[i].itemName)
        }
      }
      if (this.standardForm.publishedDate != "") {
        this.standardForm.publishedDate = this.standardForm.publishedDate.substr(0, 10)
      }
      this.isStatus = this.standardForm.status
      if (this.standardForm.createTime != undefined) {
        this.standardForm.createTime = this.standardForm.createTime.slice(0, this.standardForm.createTime.indexOf("."));
      }
      if (this.standardForm.updateTime != undefined) {
        this.standardForm.updateTime = this.standardForm.updateTime.slice(0, this.standardForm.updateTime.indexOf("."));
      }
      // this.readAllUnit();
    },
    watch: {
      // standardDetail() {
      //   for (var i in this.standardDetail) { //赋值
      //     this.standardForm[i] = this.standardDetail[i];
      //   }
      // }
      activeTab(val) {
        if (val == 'second') {
          if (process.env.NODE_ENV == 'development') {

            this.url = "../../static/workflow.html?id=" + this.standardForm.id + "&procInstType=" + this.procInstType + "&fromModel=look"

          } else {
            this.url = "static/workflow.html?id=" + this.standardForm.id + "&procInstType=" + this.procInstType + "&fromModel=look"

          }
          var that = this;
          // setTimeout(function () {
          //   let iframe = document.getElementById("workFlowIframe");
            window.addEventListener('message', that.handleMessage)
          // }, 3000)
        }
      }
    },
    methods: {
      ascQcStandar(row, index) { //上移
        if (index == 0) {
          return
        } else {
            this.standardForm.itemBeanList.splice(index - 1, 0, this.standardForm.itemBeanList[index]) //把点击的这一行插入到上一条
            this.standardForm.itemBeanList.splice(Number(index) + 1, 1) //插入成功之后删除该条 坐标为index + 1

            var itemBeanList = [];
            itemBeanList.push(this.standardForm.itemBeanList[index - 1])
            itemBeanList.push(this.standardForm.itemBeanList[index])
            // 如果是新加入的指标，即两个其中一个有id，则不用调接口
            if(itemBeanList[0].id != undefined  && itemBeanList[1].id != undefined){
              this.sortStandard(itemBeanList);
            }

        }

      },
      descQcStandar(row, index) { //下移

        if (index == this.standardForm.itemBeanList.length - 1) {
          return
        } else {
          this.standardForm.itemBeanList.splice(index + 2, 0, this.standardForm.itemBeanList[index]) //把点击的这一行插入当前坐标加2的位置
          this.standardForm.itemBeanList.splice(index, 1) //删除该条
          var itemBeanList = [];
          itemBeanList.push(this.standardForm.itemBeanList[index])
          itemBeanList.push(this.standardForm.itemBeanList[index + 1])
          // 如果是新加入的指标，即两个其中一个有id，则不用调接口
          if(itemBeanList[0].id != undefined  && itemBeanList[1].id != undefined){
             this.sortStandard(itemBeanList);
          }

        }
      },
      sortStandard(itemBeanList){
        this.$http({
              method: 'post',
              apiUrl: '/technology/updateStandardItemSort.htm',
              params: itemBeanList,
              isJson: true,
            }).then(res => {
              this.isRepeat = true;
              if (res.code == 0) {
              }
            })
      },

      handleMessage(event) {
        const data = event.data
        switch (data.cmd) {
          case 'loadingHide':
            this.WorkFlowMsg = "";
            this.loading1 = false;
            break;
          case 'errorMsg':
            this.loading1 = false;
            this.WorkFlowMsg = "没有查询到审核信息"
            break;

        }
      },
      // 审核流弹框
      reviewFlowPop() {
        this.reviewFlowShow = true;
        this.reviewData = this.standardForm;
      },
      // 关闭弹框，刷新页面
      closeRefresh() {
        this.$store.dispatch('getWorkflowList', 0).then(res => {
                this.$notify({
                    showClose: true,
                    message: '操作成功',
                    type: 'success',
                    title:"成功"
                })
            })
        this.$parent.readStandard(this.$parent.standarQuery);
        this.close('standardForm');

      },
      // 调用子元素函数 清空选中数据
      toggleSelect() {
        this.$refs.analysisitem.toggleSelection()
      },
      close(formName) {
        this.$refs[formName].resetFields();
        this.isRepeat = true;
        this.standardForm = {
          name: '',
          status: 2,
          code: "",
          type: "",
          publishedDate: "",
          description: "",
          // sampleType: "",
          parentVersion: "",
          version: "",
          // disableDate: "",
          sort: "1",
          itemBeanList: []

        };
        this.$parent.standarAddShow = false;
        this.activeTab = "first";
        this.loading1 = true;
        this.WorkFlowMsg = "";
      },
      selectedItem(val) {
        this.selectedItemval = val;
      },
      hhh(val) {
        console.log(val)
      },
      //去重并添加检测项目
      addItem() {
        for (var i = 0; i < this.selectedItemval.length; i++) {
          //转换属性
          this.selectedItemval[i].item = this.selectedItemval[i].id;
          delete this.selectedItemval[i].id;
          this.selectedItemval[i].itemName = this.selectedItemval[i].name;
          this.selectedItemval[i].itemCode = this.selectedItemval[i].code;
          this.$set(this.selectedItemval[i], 'indexName', this.selectedItemval[i].name);
          // 新选中的检测项目 默认单位为'mg/L'
          var unitId = '';
          for (var j in this.allUnit) {
            if (this.allUnit[j].ename == 'mg/L') {
              unitId = this.allUnit[j].code
            }
          }
          this.$set(this.selectedItemval[i], 'unit', unitId);
          this.$set(this.selectedItemval[i], 'unitName', 'mg/L');
        }
        this.standardForm.itemBeanList = this.util.repeatData({ old: this.standardForm.itemBeanList, new: this.selectedItemval, unique: 'item',sort:"order" })
        this.toggleSelect();
        this.analysisAddShow = false;
      },
      submitStandard(value) {
        this.$refs.standardForm.validate((valid) => { //表单验证
          if (valid) {
            if (this.newOrEdit == 'new') {
              var url = '/technology/addStandard.htm'
              var data = {
                name: this.standardForm.name,
                type: this.standardForm.type,
                description: this.standardForm.description,
                publishedDate: this.standardForm.publishedDate == '' ? null : this.standardForm.publishedDate,
                version: this.standardForm.version,
                flowType: 0,//flowType 值为1，用来区分不同审核流用的,
                itemBeanList: this.standardForm.itemBeanList
              }
              if (value == 'commit') {
                data.submitType = this.submitType.submitOpen;
              } else {
                data.submitType = this.submitType.submitDraft;
              }

            } else {
              var url = '/technology/updateStandard.htm'
              var data = {
                id: this.standardForm.id,
                name: this.standardForm.name,
                type: this.standardForm.type,
                description: this.standardForm.description,
                publishedDate: this.standardForm.publishedDate == '' ? null : this.standardForm.publishedDate,
                version: this.standardForm.version,
                flowType: 0,//flowType 值为1，用来区分不同审核流用的,
                itemBeanList: this.standardForm.itemBeanList
              }
              if (value == 'commit') {
                data.submitType = this.submitType.submitOpen;
              } else {
                data.submitType = this.submitType.submitDraft;
              }
            }
            this.isRepeat = false;
            this.$http({
              method: 'post',
              apiUrl: url,
              params: data,
              isJson: true,
               isLoading:true
            }).then(res => {
              this.isRepeat = true;
              if (res.code == 0) {
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });
                this.$parent.readStandard(this.$parent.standarQuery);
                this.close('standardForm');

              }

            }).catch(() => {

            });
          }
        })

      },
      // 删除已经选择的检测项目
      deleteItem(index) {
        this.standardForm.itemBeanList.splice(index, 1);
      },

      closeAnalysis(formName) {
        this.analysisAddShow = false;
        this.toggleSelect();
      },
      addAnalysis() {
        this.analysisAddShow = true;
      },
    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .tabName {
    display: inline-block;
    cursor: pointer;
    padding: 0px 15px;
    border: 1px solid #b7b7b7;
    border-bottom: none;
    border-radius: 5px 5px 0 0;
    color: #a9a9a9;
  }

  .activeTab {
    color: #409eff;
  }

  .standardAddcon .form {
    padding-top: 25px;
    height: 160px;
  }

  .standardAddcon .width100 {
    height: 100%;
  }

  .standardAddcon .elTab {
    height: calc(100% - 160px);
    padding: 0 20px;
  }

  .standardAddcon .elTab .el-tabs {
    height: 100%;
  }

  .standardAddcon .el-form .el-form-item {
    display: inline-block;
    width: 32%;
    margin-bottom: 15px;
  }

  .standardAddcon .el-col-22 .el-select {
    width: 100%;
  }

  .standardAddcon .el-form .el-form-item .el-date-editor {
    width: 100%;
  }
</style>
<style>
  .standardAddcon .elTab .el-tabs .el-tabs__content {
    height: calc(100% - 55px)
  }

  .standardAddcon .elTab .el-tabs .el-tab-pane {
    height: 100%;
  }

  .standardAddcon .user-footer {
    height: 35px;
    line-height: 35px;
  }

  .standardAddcon .elTab .el-tabs .el-tabs__content .el-table {
    height: calc(100% - 38px)
  }

  .analysisForm .el-form .el-form-item {
    width: 100% !important;
  }

  .analysisForm .el-dialog {
    height: 70%;
  }

  .analysisForm .el-dialog .el-form-item {
    margin-bottom: 20px;
  }

  .analysisForm .el-dialog .el-dialog__body {
    height: calc(100% - 85px);
    padding: 10px;
  }

  .analysisForm .el-dialog .el-dialog__body .form {
    height: 40px;
  }

  .analysisForm .el-dialog .el-dialog__body .analysisitem {
    height: calc(100% - 45px);
  }

  .analysisForm .el-dialog .el-dialog__footer {
    height: 45px;
    line-height: 45px;
    padding: 0 20px !important;
  }

  .analysisitem>div,
  .analysisitem>div>div {
    height: 100%;
  }

  .analysisitem .separaterowTable .tableCon {
    height: 100%;
  }



  .analysisitem .seachTip {
    height: 48px;
    padding: 10px 0px 10px 45px;
  }

  .analysisitem .seachTip .isZuJian {
    margin: 0 12px;
  }
</style>
